﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Newtonsoft.Json;
using System.IO;

namespace WebBuddy.Ajax
{
    /// <summary>
    /// Couple usefull extension methods
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// Convert a string to an object
        /// </summary>
        /// <typeparam name="T">The type of object to convert into</typeparam>
        /// <param name="json">A json string</param>
        /// <returns>Hopefully an object</returns>
        public static T FromJSON<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);

        }
        /// <summary>
        /// Convert a stream into an object
        /// </summary>
        /// <typeparam name="T">The type of object to convert into</typeparam>
        /// <param name="jsonStream">An open stream</param>
        /// <param name="objectType">The type of object you expect to get back</param>
        /// <returns>(Hopefully) an object</returns>
        public static T FromJSON<T>(this Stream jsonStream, Type objectType)
        {
            T result;

            using ( StreamReader reader = new StreamReader(jsonStream) )
            {
                JsonSerializer serializer = new JsonSerializer();
                result = (T)serializer.Deserialize(reader, objectType);

            }
            return result;
        }

        /// <summary>
        /// Convert a stream into an object
        /// </summary>
        /// <param name="jsonStream">An open stream</param>
        /// <param name="resultType">Type of object to deserialize</param>
        /// <returns>(Hopefully) an object</returns>
        public static object FromJSON(this Stream jsonStream, Type resultType)
        {

            object result;
            using ( StreamReader reader = new StreamReader(jsonStream) )
            {
                JsonSerializer serializer = new JsonSerializer();

                result = serializer.Deserialize(reader, resultType);

            }
            return result;

        }
    }
}
